<?php
namespace classlib;
use classlib\core as C;
class iplocation {
	//判断是否是内网的IP地址
	public static function islocal($ip) {
		if ($ip == 'Unknown') {
			return true;
		}
		return preg_match('/^(172|10|192)\./', $ip);
	}
	
	/**
	 * 获取用户当前所属国家的2位数编号
	 * @return string $code
	 */
	public static function country() {
		$code   = 'CN';
		$ip     = C\get_ip();
		$record = self::ip2Location($ip);
		if (isset($record['countryCode']) && $record['countryCode'] != '-') {
			$code = $record['countryCode'];
		}
		return $code;
	}
	
	/**
	 * 根据IP进行地理定位
	 * @param  string $ip
	 * @return array(countryCode,countryName,timeZone,longitude,latitude,cityName,regionName)
	 */
	public static function ip2Location($ip) {
		require_once COREDIR.'/classlib/plugins/_ip2location/IP2Location.php';
		$fileio = COREDIR.'/IP2LOCATION-LITE-DB11.BIN/IP2LOCATION-LITE-DB11.BIN';
		$db     = new \IP2Location\Database($fileio, \IP2Location\Database::FILE_IO);
		$fields = array(
			\IP2Location\Database::COUNTRY_CODE, \IP2Location\Database::COUNTRY_NAME,
			\IP2Location\Database::REGION_NAME, \IP2Location\Database::CITY_NAME,
			\IP2Location\Database::LATITUDE,  \IP2Location\Database::LONGITUDE,
			\IP2Location\Database::TIME_ZONE, \IP2Location\Database::COUNTRY,
		);
		$records = $db->lookup($ip, $fields);
		return $records;
	}
	
	/**
	 * 获取用户当前所属城市名称
	 * @return string $code
	 */
	public static function getCity($ip='') {
		if (!$ip) {
			$ip  = C\get_ip();
		}
		$records = self::ip2Location($ip);
		return $records['cityName'];
	}
}